package com.example.mycalculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	
	public static int NumberID [] = {
		R.id.button0,
		R.id.button1,
		R.id.button2,
		R.id.button3,
		R.id.button4,
		R.id.button5,
		R.id.button6,
		R.id.button7,
		R.id.button8,
		R.id.button9,
	};
	public static int ButtonID [] = {
		R.id.button0,
		R.id.button1,
		R.id.button2,
		R.id.button3,
		R.id.button4,
		R.id.button5,
		R.id.button6,
		R.id.button7,
		R.id.button8,
		R.id.button9,
		R.id.buttonDot,
		R.id.buttonEqual,
		R.id.buttonAdd,
		R.id.buttonSub,
		R.id.buttonMulty,
		R.id.buttonDivision,
		R.id.buttonMC,
		R.id.buttonMP,
		R.id.buttonMS,
		R.id.buttonMR,
		R.id.buttonON,
	};
	public TextView TextScreen;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        for (int id : ButtonID) {
			Button b =(Button) findViewById(id);
			b.setOnClickListener(this);
		}
        TextScreen = (TextView)findViewById(R.id.textScreen);
    }


    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public double saveNumber = 0;
    public boolean onEdit = false;
    public char savedExpr = ' ';
    
	public void onClick(View arg0) {
		String text = ((Button)arg0).getText().toString();
		int char0 = (int)text.charAt(0);
		
		if(text.length()==1 && (char0 >= '0') && (char0 <= '9')) {
			onNumberClick(char0 - '0');
			return;
		}
		
		if("+-*/".indexOf(text)>=0){
			onExpClick(text.charAt(0));
			return;
		}
		if(text.equals("=")){
			onEqualClick();
			return;
		}
		if(text.equals(".")){
			if(TextScreen.getText().toString().indexOf(".")<0){
				TextScreen.setText(TextScreen.getText().toString()+'.');
			}
			return;
		}
	}
	public void onNumberClick(int number){
		if(onEdit){
			if(TextScreen.length()<20){
				TextScreen.setText(TextScreen.getText().toString()+number);
			}
		}else{
			TextScreen.setText(""+number);
			onEdit = true;
		}
	}
    public void onExpClick(char c){
    	onEdit=false;
    	saveNumber = Double.parseDouble(TextScreen.getText().toString());
    	savedExpr = c;
    }
    public void onEqualClick(){
    	double screenNumber = Double.parseDouble(TextScreen.getText().toString());
    	switch(savedExpr){
		case '+':
			TextScreen.setText(""+(screenNumber+saveNumber));
			break;
		case '-':
			TextScreen.setText(""+(saveNumber-screenNumber));
			break;
		case '*':
			TextScreen.setText(""+(screenNumber*saveNumber));
			break;
		case '/':
			TextScreen.setText(""+(saveNumber/screenNumber));
			break;
		}
    	onEdit = false;
    }
    public void onMemoryClick(String s){
    	
    }
}
